Vue.http.options.emulateJSON = true;
Vue.filter('time', function (value) {//value为13位的时间戳
    function add0(m) {
        return m < 10 ? '0' + m : m
    }
    var time = new Date(parseInt(value));
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();

    return y + '-' + add0(m) + '-' + add0(d);
});
var listVue=new Vue({
	 el: '#customerListIndex',
	 data:{
		 groupId:'',
		 alltotal:'',
		 tab_2_total:'',
		 tab_3_total:'',
		 tab_4_total:'',
		 projectList:[],
		 userGroupList:[],
		 intentionLevelList:[],
		 customerStatusList:[],
		 customerOriginList:[],
		 ftContactWayList:[],
		 followModesList:[],
		 nextFollowList:[],
		 groupList:[],
		 groupUserList:[],
		 distributionParams:{},
		 params:{
			 page:1,
			 limit:10,
			 tabType:'1'
		 },
		 addFollow:{},
		 customerList:[],
		 checkboxModel:[],
		 checkboxModelTotal:"0"
		 
	 },
	 watch:{
		 'groupId':function(newValue,oldValue){
			 var _self = this;
			 if(newValue!=""&&newValue!=null){
				 var url = contextPath+"/customer/customer/returnGroupUserList";
				 var params = {
						 resourcesCode:'menu_0006_0001',
						 salesGroupId:newValue
				 };
				 _self.$http.post(url,params).then((response)=>{
					 _self.groupUserList=response.body;
				 });
			 }else{
				 _self.groupUserList=[];
			 }
		 },
		 'checkboxModel':function(newValue,oldValue){
			 var _self = this;
			 _self.checkboxModelTotal = newValue.length;
		 }
	 },
	 mounted:function(){
		 //项目
		 this.initproject();
		
		 //加载枚举
		 this.initPageEnum(1); 
		 this.initPageEnum(2);
		 //跟进方式
		 this.initPageEnum(3);
		 //客户性质
		 this.initCustomerOrigin(2);
		 this.initCustomerOrigin(11);
		//时间
		 this.initNextFollow();
	 },
	 methods:{
		
		initproject:function(){
			var _self = this;
			var url = contextPath+"/customer/follow/returnProjectName";
			var params = {
				resourcesCode:'menu_0003_0001',
				resourcesName:'resName_pro_list'
			};
			_self.$http.post(url,params).then((response) => {
				_self.projectList=response.body;
				if(response.body!=null){
					var projectId = response.body[0].id;
					_self.params.projectId = projectId;
					_self.initUser();
					
				}
			}, (response) => {
				console.log(response);
			});
		},
		initUser:function(){
			var _self = this;
			_self.params.userCode="";
			var url = contextPath+"/customer/customer/userByProjectIdForGroup";
			var p = {
					projectId:_self.params.projectId
			};
			
			_self.$http.post(url,p).then((response)=>{
				_self.userGroupList = response.body;
				_self.customerAllInfo(1);
			},(response)=>{
				console.log(response);
			});
		},initPageEnum:function(value){
			var _self = this;
			var url = contextPath+"/router/customer/getEnumJson";
			var enumParams = {
					code:value
			};
			_self.$http.post(url,enumParams).then((response)=>{
				switch(value){
				case 1:
					_self.intentionLevelList=response.body.obj;
				  break;
				case 2:
					_self.customerStatusList=response.body.obj;
				  break;
				
				case 4:
					_self.followModesList=response.body.obj;
				 break;
				}
				
			});
		},initCustomerOrigin:function(value){
			var url=contextPath+"/system/baseCodeValue/getCodeValueByType";
			var originParams = {
					typeId:value
			};
			var _self = this;
			_self.$http.post(url,originParams).then((response)=>{
				switch(value){
				case 2:
					_self.customerOriginList = response.body;
				  break;
				case 11:
					_self.ftContactWayList = response.body;
				  break;
				}
				
			});
		},customerAllInfo:function(tabType){
			var _self = this;
			var loadIndex = layer.load(0, {shade: false});
			/*var checkArea = $("input[name='check_area']");
			var valuse = "";
			for(var i=0;i<checkArea.length;i++){
				if(checkArea[i].checked){
					valuse+=checkArea[i].value+",";
				}
			}
			_self.params.rqDemandArea = valuse;*/
			var ftContactTimeBefore = $("input[name='ftContactTimeBefore']").val();
			var ftContactTimeAfter = $("input[name='ftContactTimeAfter']").val();
			var lastFollowTimeBefore = $("input[name='lastFollowTimeBefore']").val();
			var lastFollowTimeAfter = $("input[name='lastFollowTimeAfter']").val();
			_self.params.lastFollowTimeBefore = lastFollowTimeBefore;
			_self.params.lastFollowTimeAfter = lastFollowTimeAfter;
			_self.params.ftContactTimeBefore = ftContactTimeBefore;
			_self.params.ftContactTimeAfter = ftContactTimeAfter;
			var url = contextPath+'/customer/customer/customerList';
			_self.$http.post(url,_self.params).then((response)=>{
				_self.customerList=response.body.rows;
				var totalPages = response.body.totalPages;
				var current = response.body.pageNumber;
				_self.inittabCount(1);
				_self.inittabCount(2);
				_self.inittabCount(3);
				_self.inittabCount(4);
				laypage({
          		  cont: $('#pageClass'), //容器。值支持id名、原生dom对象，jquery对象,
          		  pages: totalPages, //总页数
          		  curr:current,
          		  skip: true, //是否开启跳页
          		  skin: 'molv',
          		  groups: 3, //连续显示分页数
          		  jump: function(obj,first){
          			  if(!first){
          				  _self.params.page=obj.curr;
          				  _self.customerAllInfo(tabType);
          			  }
          		  }
      			});
				layer.close(loadIndex);
			});
		},tabPage:function(tabType){
			var tab = $("li[name=tab_p]");
			for(var i=0;i<tab.length;i++){
				//移除所有的选中效果
				tab.eq(i).attr("class","");
			}
			//给当前选项增加选中效果
			$("#tab_"+tabType).attr("class","active");
			//增加查询效果
			var _self = this;
			_self.params.tabType = tabType;
			_self.params.page = 1;
			_self.customerAllInfo(tabType);
		},inittabCount:function(value){
			var _self = this;
			var url=contextPath+'/customer/customer/selectCusType';
				_self.params.tab=value;
				_self.$http.post(url,_self.params).then((response)=>{
					if(value==1){
						_self.alltotal= response.body;
					}else if(value==2){
						_self.tab_2_total= response.body;
					}else if(value==3){
						_self.tab_3_total= response.body;
					}else if(value==4){
						_self.tab_4_total= response.body;
					}
				});
		},downEcxel:function(){
			var _self = this;
			var url = contextPath+'/router/customer/customer/downExcel';
			_self.$http.post(url,null).then((response)=>{
				location.href=response.body.entity;
			});
		},importFile:function(){
			var file = $("#multipartFile").val();
			if(file==null||file==""){
				layer.alert("请选择上传EXCEL文件");
			}else{
				 var pos = file.lastIndexOf(".");  
				 var lastname = file.substring(pos,file.length);  
				 var resultName=lastname.toLowerCase(); 
				 if ('.xls'!=resultName.toString()&&'.xlsx'!=resultName.toString()){
					 layer.alert("请上传.xls或.xlsx后缀的文件!");
				 }else{
					 	var _self = this;
					 	var projectId = _self.params.projectId;
					 	var url = contextPath+'/customer/import/importExcel?projectId='+projectId;
					 	if(projectId==null||projectId==""){
					 		layer.alert("请选择项目!");
					 	}else{
					 		$.ajaxFileUpload({
								type: "POST",
								url:url,
								fileElementId:'multipartFile',
								dataType: "json",
								success: function(obj) {
									var res=obj.res;
									if(res=="1"){
										var result=obj.obj;
			                    		var successCount=result.successCount;
			                    		var errorCount=result.errorCount;
			                    		var totalCount=successCount+errorCount;
			                    		var batchId=result.batchId;
			                    		var showMsg="总计："+totalCount+"条;成功:"+successCount+"条;失败:"+errorCount+"条;";
			                    		if(errorCount>0){
			                    			//询问框
			                    			layer.confirm("提示,"+showMsg+",是否下载错误数据?", {
			                    			  btn: ['下载','取消'] //按钮
			                    			}, function(){
			                    				var downloadUrl=contextPath+"/customer/import/download?batchId="+batchId;
			                    		    	location.href=downloadUrl;
			                    		    	$('#myModalThr').modal('hide');
			                    			}, function(){
			                    				$('#myModalThr').modal('hide');
			                    			});
			                    		}else{
			                    			layer.alert("提示",showMsg);
			                    		}
									}else{
			                    		layer.alert("提示","导入失败");
			                    	}
							 }
							});
					 	}
				 }
			}
		},valid:function(){
			   $('#addFollow').bootstrapValidator({
			    	message: '必填',
			        feedbackIcons: {
			            valid: 'glyphicon glyphicon-ok',
			            invalid: 'glyphicon glyphicon-remove',
			            validating: 'glyphicon glyphicon-refresh'
			        },
			        fields:{
			        	followMode: {
			                validators: {
			                    notEmpty: {
			                        message: '请选择跟进方式'
			                    }
			                }
			            },followContents: {
			                validators: {
			                    notEmpty: {
			                        message: '请填写跟进内容'
			                    }
			                }
			            }
			        }
			    });
			   $('#addFollow').bootstrapValidator('validate');
		},showWindow:function(cusId){
			var _self = this;
			_self.valid();
			 var bootstrapValidator = $("#addFollow").data('bootstrapValidator'); 
			 bootstrapValidator.destroy();
			_self.addFollow = {};
			_self.addFollow.customerId = cusId;
			_self.addFollow.projectId = _self.params.projectId;
			$('#myModal').modal('show');
		},onSubmit:function(){
			 var _self = this;
			   _self.valid();
				var bootstrapValidator = $("#addFollow").data('bootstrapValidator'); 
			   if(bootstrapValidator.isValid()){
				   var url = contextPath+"/customer/customer/addFollow";
				   var _self = this;
				   var nextFollowQ = $("input[name='nextFollowQ']").val();
				   _self.addFollow.nextFollowQ = nextFollowQ;
				   _self.$http.post(url,_self.addFollow).then((response)=>{
				    	var body = response.body;
				    	if(body.res=="1"){
				    		layer.alert("跟进成功!");
				    		$('#myModal').modal('hide');
				    		_self.customerAllInfo(null);
				    	}else{
				    		layer.alert("系统异常,"+body.resMsg);
				    	}
				    });
			   }
			   
		},initNextFollow:function(){
			var _self = this;
			var url = contextPath+"/router/customer/customer/getTime";
			 _self.$http.post(url,null).then((response)=>{
				 _self.nextFollowList = response.body;
			 });
		},showGroup:function(projectId,customerId){
			$("#myModalTwo").modal('show');
			var _self = this;
			_self.groupId="";
			_self.distributionParams={};
			_self.distributionVaild();
			_self.distributionParams.customerId=customerId;
			var bootstrapValidator = $("#distributionForm").data('bootstrapValidator'); 
			bootstrapValidator.destroy();
			var url=contextPath+'/customer/customer/returnGroupList';
			var ps = {
					resourcesCode:'menu_0006_0001',
					projectId:projectId
			};
			_self.$http.post(url,ps).then((response)=>{
				_self.groupList = response.body;
			});
		},distributionSubmit:function(){
			 var _self = this;
			 _self.distributionVaild();
			 var bootstrapValidator = $("#distributionForm").data('bootstrapValidator'); 
			 if(bootstrapValidator.isValid()){
				 var url = contextPath+"/customer/customer/distributionConsultant";
				 _self.distributionParams.projectId =_self.groupId;
				 _self.$http.post(url,_self.distributionParams).then((response)=>{
						var body = response.body;
						if(body.res=="1"){
							layer.alert("分配成功!");
							$('#myModalTwo').modal('hide');
				    		_self.customerAllInfo(null);
						}else{
							layer.alert(body.resMsg);
						}
					});
				 
			 }
		},distributionVaild:function(){
			 $('#distributionForm').bootstrapValidator({
			    	message: '必填',
			        feedbackIcons: {
			            valid: 'glyphicon glyphicon-ok',
			            invalid: 'glyphicon glyphicon-remove',
			            validating: 'glyphicon glyphicon-refresh'
			        },
			        fields:{
			        	groupId: {
			                validators: {
			                    notEmpty: {
			                        message: '请选择销售组'
			                    }
			                }
			            },consultantUserId: {
			                validators: {
			                    notEmpty: {
			                        message: '请选择经纪人'
			                    }
			                }
			            }
			        }
			    });
			   $('#distributionForm').bootstrapValidator('validate');
		},batchDistribution:function(){
			var checkArea = $("input[name='customerCheck']");
			var valuse = "";
			for(var i=0;i<checkArea.length;i++){
				if(checkArea[i].checked){
					valuse+=checkArea[i].value+",";
				}
			}
			if(valuse==""){
				layer.alert("请勾选记录!");
			}else{
				var _self = this;
				var projectId = _self.params.projectId;
				_self.showGroup(projectId,valuse);
			}
		}, checkedAll: function() {
		      var _this = this;
		      //实现反选
		      if (_this.checkboxModel.length === _this.customerList.length) {
		        _this.checkboxModel = [];
		      } else {//实现全选
		        _this.checkboxModel = [];
		        _this.customerList.forEach(function(item) {
		          _this.checkboxModel.push(item.id);
		        });
		      }
		    },
		    bigEdit:function(){
		    	JY.Model.editBig("IndustModelDiv",'新增业态',function(){});
		    }
	 }
});